package com.example.module_filemanage.MVVM.View.Fragment;

import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.module_base.Controll.MyToolBar;
import com.example.module_filemanage.Base.FM_BaseFragment;
import com.example.module_filemanage.Interface.ICallBack;
import com.example.module_filemanage.Interface.IFileInfoOnclickListener;
import com.example.module_filemanage.MVVM.Module.Business.TranModule;
import com.example.module_filemanage.MVVM.Module.Entil.Item_FileInfo_module;
import com.example.module_filemanage.MVVM.View.Dialog.MDialog;
import com.example.module_filemanage.MVVM.ViewModule.FMFile_Info_VM;
import com.example.module_filemanage.Public.BodyColor;
import com.example.module_filemanage.R;
import com.example.module_filemanage.databinding.FmSpaceFragmentBinding;

/**
 * Created by SJ on 2018/4/20.
 */

public class FM_File_Info_fragment extends FM_BaseFragment implements View.OnClickListener {
    public static final int requestCode = 986;
    FmSpaceFragmentBinding mBinding;
    String spacename;
    FMFile_Info_VM _fmFileInfoVm;
    String[] accounts;
    Toolbar toolbar;
    PopupWindow popupWindow;
    LinearLayout _linearLayout;

    @Override
    public int setlayoutid() {
        return R.layout.fm_space_fragment;
    }

    public static FM_File_Info_fragment getInstance(String space, String[] _accounts) {
        FM_File_Info_fragment _fragment = new FM_File_Info_fragment();
        _fragment.setData(space, _accounts);
        return _fragment;
    }

    public void setData(String ISpacename, String[] _accounts) {
        spacename = ISpacename;
        accounts = _accounts;
    }

    @Override
    public void init(ViewDataBinding binding) {
        mBinding = (FmSpaceFragmentBinding) binding;

        toolbar = new MyToolBar(getContext())
                .init().addTitle(spacename)
                .addLogo()
                .addMenu(R.menu.fm_select_menu, onMenuItemClickListener)
                .setOverflowIcon()
                .setColor(R.color.darkslateblue, getResources().getColor(R.color.white))
                .addHome(1, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getFragmentManager().popBackStack();
                    }
                });

        this.addToolBar(mBinding.llSpace, toolbar, true);
        initBody();
        OnMenu(toolbar);
        binddata();

    }

    private void binddata() {
        ProgressDialog waitingDialog = new ProgressDialog(getContext());
        waitingDialog.setTitle("数据加载");
        waitingDialog.setMessage("加载中...");
        waitingDialog.setIndeterminate(true);
        waitingDialog.setCancelable(false);
        waitingDialog.show();

        _fmFileInfoVm = new FMFile_Info_VM(getContext(), mBinding, waitingDialog);
        _fmFileInfoVm.init(spacename);

        _fmFileInfoVm._fileInfo_adapter.setFileOnclickListener(new IFileInfoOnclickListener() {
            @Override
            public void deletListener(View IView, final int position, final Item_FileInfo_module item) {
                // Log.e(TAG, "deletListener: "+spacename+ item.filename);
                if (TranModule.isaccount(_fmFileInfoVm._fileInfo_adapter.getitem(position).getFilename())) {
                    MDialog.getInstance(getActivity()).delFile(item, new ICallBack<Bundle>() {
                        @Override
                        public void success(Bundle message) {
                            if (message.getInt("code") == 200) {
                                _fmFileInfoVm._fileInfo_adapter.delFileItem(position);
                            } else {
                                Toast.makeText(mContext, message.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    Toast.makeText(getActivity(), "没有权限删除！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void downloadListener(View IView, int position) {
                MDialog.getInstance(getActivity()).downloadFile(_fmFileInfoVm._fileInfo_adapter.getitem(position));
            }

            @Override
            public void showimgListener(View IView, int position) {
                String[] titles = TranModule.itemToArray(_fmFileInfoVm._fileInfo_adapter.getitem(position));
                showImg(titles);
            }

            @Override
            public void onclickListener(View IView, final int position) {
                if (TranModule.isaccount(_fmFileInfoVm._fileInfo_adapter.getitem(position).getFilename())) {
                    MDialog.getInstance(getActivity()).rename(_fmFileInfoVm._fileInfo_adapter.getitem(position), new ICallBack<String>() {
                        @Override
                        public void success(String spacename) {
                            _fmFileInfoVm._fileInfo_adapter.changename(position, spacename);
                        }
                    });
                } else {
                    Toast.makeText(getActivity(), "没有权限修改！", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    //菜单监听事件

    private Toolbar.OnMenuItemClickListener onMenuItemClickListener = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            int i = item.getItemId();
            if (i == R.id.menu_selectname) {
                popupWindow.showAsDropDown(toolbar, getMesurewidth() - _linearLayout.getWidth(), 0);
            } else if (i == R.id.menu_refreshfile) {
                binddata();
            }else if (i==R.id.menu_uploadfile){
                new AlertDialog.Builder(getActivity()) // build AlertDialog
                        .setTitle("选择类型(图片建议压缩)") // title
                        .setItems(R.array.upload_select, new  DialogInterface.OnClickListener() { //content
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which){
                                    case 0:
                                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                        intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                                        getActivity().startActivityForResult(intent,requestCode);
                                        break;
                                    case 1:
                                        Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
                                        intent2.setType("image/*");//选择图片  
                                        intent2.addCategory(Intent.CATEGORY_OPENABLE);
                                        getActivity().startActivityForResult(intent2,requestCode);
                                        break;

                                }

                            }
                        }) .show();

            }
            return true;
        }
    };

    //跳转放大图片界面
    private void showImg(String[] titles){
        if (titles[2].matches(".+\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)")) {
            getFragmentManager().beginTransaction().addToBackStack(null)
                    .setCustomAnimations(R.anim.in_from_left, R.anim.in_from_right, R.anim.out_from_left, R.anim.out_from_right)
                    .add(R.id.drawer_layout, FM_ShowPicture_fragment.getInstance(titles))
                    .commit();
        }
    }
    private void initBody() {
        toolbar.setBackgroundColor(getResources().getColor(BodyColor.maincolor));
        mBinding.llSpace.setBackgroundColor(getResources().getColor(BodyColor.maincolor));
        mBinding.recFileinfo.setBackgroundColor(getResources().getColor(BodyColor.background));
    }
    //ID
    @android.support.annotation.IdRes
    private static final int ID=378;
    //菜单点击事件
    @Override
    public void onClick(View IView) {
        int id=IView.getId()-ID;
        switch (id){
            case 0:
                _fmFileInfoVm._fileInfo_adapter.selectAllname();
                break;
            default:
                _fmFileInfoVm._fileInfo_adapter.selectName(accounts[id-1]);
                break;
        }


    }
//添加菜单

    public void OnMenu(View view){
        // 获取自定义的菜单布局文件
        _linearLayout=new LinearLayout(getContext());
        LinearLayout.LayoutParams _params=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        _linearLayout.setLayoutParams(_params);
        _linearLayout.setOrientation(LinearLayout.VERTICAL);
        _linearLayout.setElevation(20.0f);
        /**=========================================================*/
        View popupWindow_view = getActivity().getLayoutInflater().inflate(R.layout.fm_item_menu, null,false);
        popupWindow_view.setId(ID);
        ((TextView)popupWindow_view.findViewById(R.id.tv_account)).setText("全部");
        popupWindow_view.setOnClickListener(this);
        _linearLayout.addView(popupWindow_view,0,_params);
        for (int i=0; i < accounts.length; i++) {
            popupWindow_view = getActivity().getLayoutInflater().inflate(R.layout.fm_item_menu, null,false);
            popupWindow_view.setId(ID+i+1);
            ((TextView)popupWindow_view.findViewById(R.id.tv_account)).setText(accounts[i]);
            popupWindow_view.setOnClickListener(this);
            _linearLayout.addView(popupWindow_view,i+1,_params);
        }
        // 创建PopupWindow实例,设置菜单宽度和高度为包裹其自身内容
        popupWindow=new PopupWindow(_linearLayout, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        //设置菜单显示在按钮的下面
        //popupWindow.showAsDropDown(view,getMesurewidth()-_linearLayout.getWidth(),0);
    }
    //
    private int getMesurewidth(){
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return   outMetrics.widthPixels;
    }
    //上传文件/图片
    public void upLoadFile(final String filepath) {
        MDialog.getInstance(getActivity()).upLoadFile(filepath,spacename);
    }

    //压缩文件




}
